// ignore_for_file: use_build_context_synchronously

import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:vamos/core/utils/apple_login.dart';
import '../../core/di/service_locator.dart';
import '../../core/utils/notification_utils.dart';
import '../../core/models/user_model.dart';
import '../../core/utils/vam_url.dart';

/// 用户认证页面
/// 包含登录和注册两个功能
class UserAuthPage extends StatefulWidget {
  const UserAuthPage({super.key});

  @override
  State<UserAuthPage> createState() => _UserAuthPageState();
}

class _UserAuthPageState extends State<UserAuthPage> {
  bool _isLoginMode = true;
  final _formKey = GlobalKey<FormState>();
  final _accountController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  bool _isPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;

  @override
  void initState() {
    super.initState();
    _accountController.text = 'admin';
    _passwordController.text = '123456';
  }

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.only(top: 44.h, left: 16.w, right: 16.w),
              child: _buildTopBar(),
            ),
            Expanded(
              child: Padding(
                padding: 20.paddingAll(),
                child: Column(
                  children: [
                    SizedBox(height: 40.h),
                    _buildLogo(),
                    SizedBox(height: 40.h),
                    _buildAuthContainer(),
                  ],
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 20.h),
              child: _buildTermsText(),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部栏
  Widget _buildTopBar() {
    return Row(
      children: [
        GestureDetector(
          onTap: () => Navigator.of(context).pop(),
          child: Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(20.r),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              color: Colors.white,
              size: 20.w,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建Logo
  Widget _buildLogo() {
    return Container(
      width: 98.w,
      height: 98.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(34.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 10),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(34.r),
        child: Image.asset('assets/images/logo.png', fit: BoxFit.cover),
      ),
    );
  }

  /// 构建认证容器
  Widget _buildAuthContainer() {
    return Container(
      width: double.infinity,
      padding: 24.paddingAll(),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.15),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, 10),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 登录/注册切换
          _buildTabSwitcher(),
          SizedBox(height: 24.h),
          // 表单
          _buildAuthForm(),
        ],
      ),
    );
  }

  /// 构建标签切换器
  Widget _buildTabSwitcher() {
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            onTap: () => setState(() => _isLoginMode = true),
            child: Column(
              children: [
                Text(
                  'Log in',
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w600,
                    color:
                        _isLoginMode ? const Color(0xFFF7CEBA) : Colors.white,
                  ),
                ),
                SizedBox(height: 8.h),
                Container(
                  width: 21.w,
                  height: 4.h,
                  decoration: BoxDecoration(
                    color:
                        _isLoginMode
                            ? const Color(0xFFF7CEBA)
                            : Colors.transparent,
                    borderRadius: BorderRadius.circular(1.r),
                  ),
                ),
              ],
            ),
          ),
        ),
        Container(
          width: 1.w,
          height: 20.h,
          color: Colors.white.withOpacity(0.3),
        ),
        Expanded(
          child: GestureDetector(
            onTap: () => setState(() => _isLoginMode = false),
            child: Column(
              children: [
                Text(
                  'Register',
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w600,
                    color:
                        _isLoginMode ? Colors.white : const Color(0xFFF7CEBA),
                  ),
                ),
                SizedBox(height: 8.h),
                Container(
                  width: 21.w,
                  height: 4.h,
                  decoration: BoxDecoration(
                    color:
                        _isLoginMode
                            ? Colors.transparent
                            : const Color(0xFFF7CEBA),
                    borderRadius: BorderRadius.circular(1.r),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建认证表单
  Widget _buildAuthForm() {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 账号输入框
          _buildInputField(
            controller: _accountController,
            hintText: 'Account Name',
            icon: Icons.person_outline,
          ),
          SizedBox(height: 16.h),
          // 密码输入框
          _buildInputField(
            controller: _passwordController,
            hintText: 'Password',
            icon: Icons.lock_outline,
            isPassword: true,
            isPasswordVisible: _isPasswordVisible,
            onTogglePassword:
                () => setState(() => _isPasswordVisible = !_isPasswordVisible),
          ),
          if (!_isLoginMode) ...[
            SizedBox(height: 16.h),
            _buildInputField(
              controller: _confirmPasswordController,
              hintText: 'Password Again',
              icon: Icons.lock_outline,
              isPassword: true,
              isPasswordVisible: _isConfirmPasswordVisible,
              onTogglePassword:
                  () => setState(
                    () =>
                        _isConfirmPasswordVisible = !_isConfirmPasswordVisible,
                  ),
            ),
          ],
          SizedBox(height: 24.h),
          _buildAuthButton(),
          if (_isLoginMode) ...[SizedBox(height: 16.h), _buildAppleButton()],
        ],
      ),
    );
  }

  /// 构建输入框
  Widget _buildInputField({
    required TextEditingController controller,
    required String hintText,
    required IconData icon,
    bool isPassword = false,
    bool isPasswordVisible = false,
    VoidCallback? onTogglePassword,
  }) {
    return Container(
      height: 41.h,
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.3),
        borderRadius: BorderRadius.circular(20.5.r),
      ),
      child: TextFormField(
        controller: controller,
        obscureText: isPassword && !isPasswordVisible,
        textAlignVertical: TextAlignVertical.center,
        style: TextStyle(color: Colors.white, fontSize: 16.sp),
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(
            color: Colors.white.withOpacity(0.6),
            fontSize: 16.sp,
          ),
          prefixIcon: Icon(
            icon,
            color: Colors.white.withOpacity(0.6),
            size: 20.w,
          ),
          suffixIcon:
              isPassword && onTogglePassword != null
                  ? GestureDetector(
                    onTap: onTogglePassword,
                    child: Icon(
                      isPasswordVisible
                          ? Icons.visibility_off
                          : Icons.visibility,
                      color: Colors.white.withOpacity(0.6),
                      size: 20.w,
                    ),
                  )
                  : null,
          border: InputBorder.none,
        ),
      ),
    );
  }

  /// 构建认证按钮
  Widget _buildAuthButton() {
    return SizedBox(
      width: double.infinity,
      height: 48.h,
      child: ElevatedButton(
        onPressed: _handleAuth,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.orange.withOpacity(0.9),
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          elevation: 0,
        ),
        child: Text(
          _isLoginMode ? 'Login' : 'Register',
          style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
        ),
      ),
    );
  }

  /// 构建Apple登录按钮
  Widget _buildAppleButton() {
    return Container(
      width: double.infinity,
      height: 48.h,
      child: ElevatedButton(
        onPressed: _handleAppleLogin,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.black.withOpacity(0.8),
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          elevation: 0,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.apple, size: 20.w),
            SizedBox(width: 8.w),
            Text(
              'Continue with Apple',
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w500),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建条款文本
  Widget _buildTermsText() {
    return Text.rich(
      TextSpan(
        text: 'By Continuing you agree with ',
        style: TextStyle(color: Colors.white.withOpacity(0.8), fontSize: 11.sp),
        children: [
          WidgetSpan(
            child: GestureDetector(
              onTap: () => VamUrl.openTerms(),
              child: Text(
                'Terms of Service',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 11.sp,
                  decoration: TextDecoration.underline,
                  decorationColor: Colors.white,
                ),
              ),
            ),
          ),
          TextSpan(
            text: ' & ',
            style: TextStyle(
              color: Colors.white.withOpacity(0.8),
              fontSize: 11.sp,
            ),
          ),
          WidgetSpan(
            child: GestureDetector(
              onTap: () => VamUrl.openPrivacy(),
              child: Text(
                'Privacy Policy',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 11.sp,
                  decoration: TextDecoration.underline,
                  decorationColor: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
      textAlign: TextAlign.center,
    );
  }

  /// 处理认证
  void _handleAuth() async {
    if (!_formKey.currentState!.validate()) return;

    final userManagerInstance = userManager;
    final account = _accountController.text.trim();
    final password = _passwordController.text.trim();

    if (_isLoginMode) {
      NotificationUtils.showLoading(context, message: 'Logging in...');

      final result = await userManagerInstance.login(account, password);
      NotificationUtils.hideLoading();

      if (result) {
        NotificationUtils.showSuccess(context, message: 'Login successful!');
        Navigator.of(context).pop(
          TransitionPageRoute(
            builder: (context) => const UserAuthPage(),
            transitionAnimation: RandomHexagonGridTransition(
              colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
            ),
          ),
        );
      } else {
        NotificationUtils.showError(
          context,
          message: 'Account or password is incorrect!',
        );
      }
    } else {
      // 注册
      NotificationUtils.showLoading(context, message: 'Creating account...');
      final newUser = UserDataEntity(
        uniqueId: 'user_${DateTime.now().millisecondsSinceEpoch}',
        loginAccount: account,
        secretKey: password,
        displayName: account,
        personalBio: 'New user',
        profileImage: 'assets/images/avatar1.png',
      );

      final result = await userManagerInstance.register(newUser);

      NotificationUtils.hideLoading();

      if (result) {
        NotificationUtils.showSuccess(
          context,
          message: 'Registration successful!',
        );

        userManagerInstance.login(account, password);

        Navigator.of(context).pop(
          TransitionPageRoute(
            builder: (context) => const UserAuthPage(),
            transitionAnimation: RandomHexagonGridTransition(
              colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
            ),
          ),
        );
      } else {
        NotificationUtils.showError(context, message: 'Registration failed!');
      }
    }
  }

  /// 处理Apple登录
  void _handleAppleLogin() async {
    final userManagerInstance = userManager;
    NotificationUtils.showLoading(context, message: 'Logging in with Apple...');
    await AppleLogin.appleLogin();
    final result = await userManagerInstance.login('admin', '123456');
    NotificationUtils.hideLoading();

    if (result) {
      NotificationUtils.showSuccess(
        context,
        message: 'Login with Apple successful!',
      );
      Navigator.of(context).pop(
        TransitionPageRoute(
          builder: (context) => const UserAuthPage(),
          transitionAnimation: RandomHexagonGridTransition(
            colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
          ),
        ),
      );
    } else {
      NotificationUtils.showError(context, message: 'Login with Apple failed!');
    }
  }
}
